<template>
  <div>
    <div class="block">
      <span class="demonstration">状态:</span>
      <el-select v-model="searchEntity.status" placeholder="请选择">
        <el-option label="全部" value=""></el-option>
        <el-option label="显示" :value="0"></el-option>
        <el-option label="隐藏" :value="1">
        </el-option>
      </el-select>
      &emsp;&emsp;&emsp;
      <span class="demonstration">商品搜索:</span>
      <el-input placeholder="请输入内容" style="width:250px" v-model='searchEntity.name'></el-input>
      <el-button type="primary" round @click="getCategoryTree()">查询</el-button>
    </div>
    <el-table :data="categoryList" style="width: 100%" row-key="id" border lazy
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column prop="name" label="名称">
      </el-table-column>
      <el-table-column prop="imgUrl" label="分类图片">
        <template slot-scope="scope">
          <el-image style="width: 50px; height: 50px" :src="scope.row.imgUrl"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="orderCloum" label="排序">
      </el-table-column>
      <el-table-column label="显示状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-color="rgba(67, 129, 230, 1)" inactive-color="#ff4949"
            :active-value="0" :inactive-value="1" @change="changeStatus($event,scope.row,scope.$index)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="addCategory(scope.row.id)" type="text" size="small">添加子目录</el-button>
          <el-button @click="updateCategory(scope.row.id)" type="text" size="small">编辑</el-button>
          <el-button type="text" v-if="scope.row.children==null" size="small" @click="deleteById(scope.row.id)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-backtop target=".page-component__scroll .el-scrollbar__wrap"></el-backtop>
    <!-- Form -->
    <el-dialog title="创建产品分类" :rules="rules" :visible.sync="dialogFormVisible">
      {{category}}
      <el-form :model="category" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="category.name"></el-input>
        </el-form-item>
        <el-form-item label="父级" prop="parentId">
          <el-input v-model="parentName" readonly></el-input>
        </el-form-item>
        <el-form-item label="分类图标" prop="imgUrl">
          <el-upload class="avatar-uploader" action="http://localhost:8001/coco/third/oss/uploadImg" :headers="headers"
            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imgUrl" :src="imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序" prop="orderCloum">
          <template>
            <el-input-number v-model="category.orderCloum" :min="1" :max="10" label="描述文字"></el-input-number>
          </template>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="category.status" active-text="开启" inactive-text="关闭" active-color="#13ce66"
            :active-value="0" :inactive-value="1" inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitCategory('ruleForm')">创建</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- Form -->
    <el-dialog title="编辑" :rules="rules" :visible.sync="updDialogFormVisible">
      <el-form :model="category" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="category.name"></el-input>
        </el-form-item>
        <el-form-item label="分类图标" prop="imgUrl">
          <el-upload class="avatar-uploader" action="http://localhost:8001/coco/third/oss/uploadImg" :headers="headers"
            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imgUrl" :src="imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序" prop="orderCloum">
          <template>
            <el-input-number v-model="category.orderCloum" :min="1" :max="10" label="描述文字"></el-input-number>
          </template>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doUpdateCategory('ruleForm')">修改</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data () {
    //这里存放数据
    return {
      token: "",
      categoryList: [],
      searchEntity: {},
      dialogFormVisible: false,
      updDialogFormVisible: false,
      category: {
        imgUrl: "",
        isDelete: 0,
      },
      imgUrl: "",
      parentName: "",
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
    };
  },
  //计算属性 类似于 data 概念
  computed: {
    headers () {
      return {
        "token": (localStorage.token || ""),
        "type": "1"
      }
    }
  },
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    doUpdateCategory () {//修改
      this.$http
        .put('http://localhost:8001/coco/goods/category/update', this.category, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          if (data.code == 0) {
            this.$message({
              message: '修改分类成功!',
              type: 'success'
            });
            this.getCategoryTree();
            this.updDialogFormVisible = false;
          } else {
            this.$message.error('修改分类失败!');
          }
        }).catch((err) => { });
    },
    updateCategory (id) {//编辑
      this.updDialogFormVisible = true;
      this.$http
        .get('http://localhost:8001/coco/goods/category/findOne?id=' + id, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          this.category = data.data;
          this.imgUrl = data.data.imgUrl;
        }).catch((err) => { });
    },
    submitCategory () {//创建子目录
      this.$http
        .post('http://localhost:8001/coco/goods/category/addCategory', this.category, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          if (data.code == 0) {
            this.$message({
              message: '添加分类成功!',
              type: 'success'
            });
            this.getCategoryTree();
            this.dialogFormVisible = false;
          } else {
            this.$message.error('添加分类失败!');
          }
        }).catch((err) => { });
    },
    handleAvatarSuccess (res, file) {//上传成功回调
      console.log(res);
      this.imgUrl = res;
      this.category.imgUrl = this.imgUrl;
    },
    beforeAvatarUpload (file) {//上传前
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    addCategory (id) {//添加子目录
      this.dialogFormVisible = true;
      this.imgUrl = "";
      this.category = { orderCloum: 1 };
      this.$http
        .get('http://localhost:8001/coco/goods/category/findOne?id=' + id, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          this.parentName = data.data.name;
          this.category.parentId = data.data.id;
        }).catch((err) => { });
    },
    deleteById (id) {//逻辑删除
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .delete("http://localhost:8001/coco/goods/category/deleteById/" + id, {
            headers: {
              "token": this.token,
              "type": "1"
            }
          })
          .then(({ data }) => {
            if (data.code == 0) {
              this.$message({
                message: '删除分类成功!',
                type: 'success'
              });
              this.getCategoryTree();
            } else {
              this.$message.error('删除分类失败!');
            }
          }).catch((err) => { });
      })


    },
    getCategoryTree () {//获取分类列表
      this.$http
        .post("http://localhost:8001/coco/goods/category/searchCategory", this.searchEntity, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          console.log(data);

          if (data.code != 0) {
            this.$message({
              message: data.message,
              type: 'error'
            })
            this.$router.push("/");
          }
          this.categoryList = data.data;
        }).catch((err) => { });
    },
    changeStatus (data, row, index) {//上下架操作
      console.log(data, row, index);
      this.$http
        .put("http://localhost:8001/coco/goods/category/updStatus/" + row.id + "/" + data, {}, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          console.log(data);
          if (data.code == 0) {
            this.$message({
              message: '修改成功!',
              type: 'success'
            });
            this.reloadList(this.num);
          } else {
            let newData = b;
            newData.publishStatus = newData.publishStatus == 1 ? "0" : "1";
            this.goodsList[index] = newData;
          }
        })
        .catch((err) => { });
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created () {
    this.token = localStorage.getItem("token");
    this.getCategoryTree();
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted () {

  },
  beforeCreate () { }, //生命周期 - 创建之前
  beforeMount () { }, //生命周期 - 挂载之前
  beforeUpdate () { }, //生命周期 - 更新之前
  updated () { }, //生命周期 - 更新之后
  beforeDestroy () { }, //生命周期 - 销毁之前
  destroyed () { }, //生命周期 - 销毁完成
  activated () { }, //如果页面有 keep-alive 缓存功能，这个函数会触发
}
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>